﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using Telerik.WinControls.Data;
using Telerik.WinControls.UI;
using Telerik.WinControls.UI.Export;

namespace SakeVar
{
    public partial class DlgDataInput : Telerik.WinControls.UI.RadForm
    {
        private static int VariableIndex = 0;
        private static int LengthIndex = 1;
        private static int DecimalIndex = 2;
        private static int CalculatedIndex = 3;
        private static int SuggestedIndex = 4;
        private ExcelDataReader.ExcelDataReader spreadsheetConcept = null;

        public StringBuilder sb { get; private set; }
        private DataTable tbInput;
        private bool IsForSAS;

        public DlgDataInput(DataTable tb, bool isSAS)
        {
            InitializeComponent();
            IsForSAS = isSAS;
            tbInput = tb;
            radGridViewInput.DataSource = tb;

            // Variable
            radGridViewInput.Columns[VariableIndex].TextAlignment = ContentAlignment.MiddleCenter;
            radGridViewInput.Columns[VariableIndex].Width = 100;
            radGridViewInput.Columns[VariableIndex].ReadOnly = true;

            // Length
            radGridViewInput.Columns[LengthIndex].Width = 50;
            radGridViewInput.Columns[LengthIndex].TextAlignment = ContentAlignment.MiddleCenter;
            radGridViewInput.Columns[LengthIndex].ReadOnly = true;

            //decimal
            radGridViewInput.Columns[DecimalIndex].Width = 50;
            radGridViewInput.Columns[DecimalIndex].TextAlignment = ContentAlignment.MiddleCenter;
            radGridViewInput.Columns[DecimalIndex].ReadOnly = true;

            // Calculated
            radGridViewInput.Columns[CalculatedIndex].Width = 100;
            radGridViewInput.Columns[CalculatedIndex].ReadOnly = true;

            //suggested
            radGridViewInput.Columns[SuggestedIndex].Width = 100;

            radGridViewInput.MasterTemplate.EnableGrouping = false;
            radGridViewInput.AllowColumnReorder = false;
            radGridViewInput.AllowColumnChooser = false;

            radMenuItemCalculate_Click(this, EventArgs.Empty);
        }

        private void radMenuItemCalculate_Click(object sender, EventArgs e)
        {
            radGridViewInput.EndEdit();

            int start = 1;
            foreach (GridViewRowInfo rowInfo in radGridViewInput.ChildRows)
            {
                try
                {
                    int len = int.Parse(rowInfo.Cells[LengthIndex].Value.ToString());
                    if (rowInfo.Cells[SuggestedIndex].Value != null && rowInfo.Cells[SuggestedIndex].Value.ToString().Length > 0)
                    {
                        start = int.Parse(rowInfo.Cells[SuggestedIndex].Value.ToString());
                    }
                    rowInfo.Cells[CalculatedIndex].Value = start.ToString() + " - " + (start + len - 1).ToString();
                    start += len;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error " + ex.Message);
                }
            }
        }

        private void radMenuItemXport_Click(object sender, EventArgs e)
        {
            DataTable tb = radGridViewInput.DataSource as DataTable;
            sb = new StringBuilder();

            if (IsForSAS == false)
                sb.Append("DATA LIST FILE=INPUTX/").Append(Environment.NewLine);

            int varPad = IsForSAS ? 24 : 26;

            foreach (DataRow row in tb.Rows)
            {
                string var = row[VariableIndex].ToString();
                sb.Append(var);
                sb.Append(' ', varPad - var.Length);
                sb.Append(row[CalculatedIndex].ToString());
                string dec = row[DecimalIndex].ToString();
                if (dec.Length > 0)
                {
                    if (IsForSAS)
                    {
                        sb.Append(' ', 21);
                        sb.Append(".").Append(dec);
                    }
                    else
                    {
                        sb.Append(' ', 18);
                        sb.Append("(,").Append(dec).Append(")");
                    }
                }
                sb.Append(Environment.NewLine);
            }

            if (IsForSAS == false)
                sb.Remove(sb.Length - 1, 1); sb.Append('.');

            this.DialogResult = DialogResult.OK;


        }

        #region Excel export

        /// <summary>Excel Export Event</summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void radMenuItemExportExcel_Click(object sender, EventArgs e)
        {
            RunExportToExcelML();
        }

        /// <summary> Export Grid to Excel </summary>
        private void RunExportToExcelML()
        {
            try
            {
                ExportToExcelML excelExporter = new ExportToExcelML(radGridViewInput);

                excelExporter.SummariesExportOption = SummariesOption.ExportAll;
                //set export settings
                excelExporter.ExportVisualSettings = false;
                excelExporter.ExportHierarchy = true;
                excelExporter.HiddenColumnOption = HiddenOption.DoNotExport;

                this.Cursor = Cursors.WaitCursor;
                saveFileDialog.Filter = "Excel (*.xls)|*.xls";
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    excelExporter.RunExport(saveFileDialog.FileName);

                    DialogResult dr = RadMessageBox.Show("The data in the grid was exported successfully. Do you want to open the file?",
                        "Export to Excel", MessageBoxButtons.YesNo, RadMessageIcon.Question);
                    if (dr == DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start(saveFileDialog.FileName);
                    }
                }
            }
            catch (Exception ex)
            {
                RadMessageBox.SetThemeName(this.radGridViewInput.ThemeName);
                RadMessageBox.Show(this, ex.Message, "I/O Error", MessageBoxButtons.OK, RadMessageIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        #endregion

        private ExcelDataReader.ExcelDataReader LoadSources(string propertyPath)
        {
            ExcelDataReader.ExcelDataReader spreadsheet = null;
            if (propertyPath == null)
                throw new ApplicationException("Please provides path.");

            FileStream fs = null;
            try
            {
                fs = new FileStream(propertyPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                spreadsheet = new ExcelDataReader.ExcelDataReader(fs);
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }

            return spreadsheet;
        }

        private void radMenuItemImport_Click(object sender, EventArgs e)
        {
            try
            {
                using (new SdmxMl.Helper.CWaitCursor())
                {

                    OpenFileDialog of = new OpenFileDialog();
                    of.Filter = "Excel (*.xls)|*.xls";
                    if (of.ShowDialog() == DialogResult.OK)
                    {
                        radGridViewInput.BeginUpdate();

                        spreadsheetConcept = LoadSources(of.FileName);
                        DataTable dt = spreadsheetConcept.WorkbookData.Tables[0];
                        tbInput.Rows.Clear();
                        for (int i = 1; i < dt.Rows.Count; i++)
                        {
                            string suggested = dt.Rows[i][4].ToString();
                            object ob = null;
                            if (suggested.Length > 0)
                                ob = int.Parse(suggested);
                            tbInput.Rows.Add(new object[] { dt.Rows[i][0], dt.Rows[i][1], dt.Rows[i][2], dt.Rows[i][3], ob });
                        }

                        radGridViewInput.EndUpdate();

                        radMenuItemCalculate_Click(this, EventArgs.Empty);
                    }
                }
            }
            catch (Exception ex)
            {
                RadMessageBox.Show(this, ex.Message, "I/O Error", MessageBoxButtons.OK, RadMessageIcon.Error);
            }

        }

    }
}
